package com.app.action.game;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.app.bean.game.SNSUserInfo;
import com.app.bean.game.Userinfo;
import com.app.bean.game.WeixinOauth2Token;
import com.app.frame.BaseAction;
import com.app.frame.support.util.AdvancedUtil;
import com.app.frame.support.util.ConfigProperty;
import com.app.frame.support.util.JsonUtil;
import com.app.frame.support.util.SignUtil;
import com.app.service.game.UserinfoService;
import com.app.service.game.WechatService;

@Controller
public class OAuthAction2 extends BaseAction {
	private final static Logger log = Logger.getLogger(OAuthAction2.class);

	// 自动注入，不需要生成set方法了，required=false表示没有实现类，也不会报错
	@Autowired(required = false)
	private WechatService wechatService;

	@Autowired(required = false)
	private UserinfoService userinfoService;

	
	public WechatService getWechatService() {
		return wechatService;
	}

	public void setWechatService(WechatService wechatService) {
		this.wechatService = wechatService;
	}

	public UserinfoService getUserinfoService() {
		return userinfoService;
	}

	public void setUserinfoService(UserinfoService userinfoService) {
		this.userinfoService = userinfoService;
	}

	// 授权接口
	@RequestMapping("/weixin")
	public String weixin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();

			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					System.out.println("参数：" + paramName + "=" + paramValue);
					session.setAttribute(paramName, paramValue);
					Cookie cookie = new Cookie(paramName, paramValue);
					response.addCookie(cookie);
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		String code = request.getParameter("code");
		if (code == null || code.equals("")) {
			index(request, response);
		} else {
			log.info(code);
			try {
				if (!"authdeny".equals(code)) {
					// 获取网页access_token
					log.info(ConfigProperty.getProperty("appId"));
					WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(
							ConfigProperty.getProperty("appId"), ConfigProperty.getProperty("appSecret"), code);
					if (null == weixinOauth2Token) {
						index(request, response);
					} else {
						String openId = weixinOauth2Token.getOpenId();
						if(ConfigProperty.getProperty("scope").equals("snsapi_userinfo")){
							String accessToken = weixinOauth2Token.getAccessToken();
							SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
							wechatService.saveUserinfo(snsUserInfo);
							Cookie cookie1 = new Cookie("openid", snsUserInfo.getOpenid());
							Cookie cookie2 = new Cookie("nickname", URLEncoder.encode(snsUserInfo.getNickname(), "utf-8"));
							Cookie cookie3 = new Cookie("headimgurl", snsUserInfo.getHeadimgurl());
							Cookie cookie4 = new Cookie("sex", String.valueOf(snsUserInfo.getSex()));
							Cookie cookie5 = new Cookie("country", snsUserInfo.getCountry());
							Cookie cookie6 = new Cookie("province", snsUserInfo.getProvince());
							Cookie cookie7 = new Cookie("city", snsUserInfo.getCity());
							response.addCookie(cookie1);
							response.addCookie(cookie2);
							response.addCookie(cookie3);
							response.addCookie(cookie4);
							response.addCookie(cookie5);
							response.addCookie(cookie6);
							response.addCookie(cookie7);
							Userinfo ul = new Userinfo();
							ul.setOpenid(openId);
							List<Userinfo> list = new ArrayList<Userinfo>();
							list = userinfoService.getUserinfo(ul);
							if(list!=null&&!list.isEmpty()){  //是否是新用户
								Cookie ifnew = new Cookie("ifnew", "new");
								response.addCookie(ifnew);
							}else{
								Cookie ifnew = new Cookie("ifnew", "old");
								response.addCookie(ifnew);
							}
						}else if(ConfigProperty.getProperty("scope").equals("snsapi_base")){
							Cookie cookie1 = new Cookie("openid", openId);
							response.addCookie(cookie1);
							session.setAttribute("openid", openId);
						}
						request.getRequestDispatcher("index.html").forward(request, response);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				map.put("status", "99");
				map.put("desc", "失败");
				JsonUtil.outJson(map, response);
				return null;
			}
		}
		return null;
	}

	// 分享接口
	@RequestMapping("/Share")
	public void Share(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			StringBuffer homeUrl = new StringBuffer();
			homeUrl.append(request.getParameter("homeurl"));

			long timestamp = System.currentTimeMillis() / 1000;

			String nonceStr = UUID.randomUUID().toString();

			String signature = null;
			String ticket = wechatService.getTicketFromDb(ConfigProperty.getProperty("appId"));
			try {
				signature = SignUtil.getSignature(ticket, nonceStr, timestamp, homeUrl.toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			map.put("appid", ConfigProperty.getProperty("appId"));
			map.put("timestamp", timestamp);
			map.put("noncestr", nonceStr);
			map.put("signature", signature);
			JsonUtil.outJson(map, response);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", "99");
			map.put("desc", "失败");
			JsonUtil.outJson(map, response);
		}
	}


	public void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 设置编码
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("utf-8");

		String redirect_uri = ConfigProperty.getProperty("oauthurl");// 目标访问地址
		redirect_uri = URLEncoder.encode(redirect_uri, "UTF-8");// 授权后重定向的回调链接地址，请使用urlencode对链接进行处理（文档要求）
		// 按照文档要求拼接访问地址
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ConfigProperty.getProperty("appId")
				+ "&redirect_uri=" + redirect_uri
				+ "&response_type=code&scope="+ConfigProperty.getProperty("scope")+"&state=STATE#wechat_redirect";
		resp.sendRedirect(url);// 跳转到要访问的地址
	}


}
